//
//   SelectionDialogView.swift
//  DKE-Album
//
//  Created by dagny on 2025/9/22.
//  Copyright © 2025 杨东宝. All rights reserved.
//

import Foundation
import UIKit
// 选择回调类型
typealias SelectionHandler = (Int) -> Void

class SelectionDialogView: UIView {
    
    // MARK: - 属性
    private var items: [SelectItemModel] = []
    private var selectedIndex: Int?
    private var selectionHandler: SelectionHandler?
    
    // 最大高度限制
    var maxHeight: CGFloat = kScreenHeight - DIMENSION_VALUE(150) {
        didSet {
            updateContainerConstraints()
        }
    }
    // 标题
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.font = DIMENSION_FONT_OF_SIZE(16)
        label.textAlignment = .center
        label.textColor = .white
        return label
    }()
    
    // 取消按钮
    private let cancelButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("cancel".localized, for: .normal)
        button.titleLabel?.font = DIMENSION_FONT_OF_SIZE(18)
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = HexRGB(0x2D3455)
        button.layer.cornerRadius = 22
        return button
    }()
    
    // 表格视图
    private let tableView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.isScrollEnabled = false
        return tableView
    }()
    
    // 容器视图
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = HexRGB(0x1E223D)
        view.layer.cornerRadius = 16
        view.clipsToBounds = true
        return view
    }()
    
    // 约束
    private var containerHeightConstraint: NSLayoutConstraint!
    
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    convenience init(title: String, items: [SelectItemModel], selectedIndex: Int? = nil, selectionHandler: SelectionHandler? = nil) {
        self.init(frame: .zero)
        self.titleLabel.text = title
        self.items = items
        self.selectedIndex = selectedIndex
        self.selectionHandler = selectionHandler
        self.tableView.reloadData()
        updateContainerConstraints()
    }
    
    // MARK: - UI 设置
    private func setupUI() {
        backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
        // 设置表格
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(SelectionCell.self, forCellReuseIdentifier: "SelectionCell")
        
        // 添加子视图
        addSubview(containerView)
        containerView.addSubview(titleLabel)
        containerView.addSubview(tableView)
        containerView.addSubview(cancelButton)
        
        // 设置约束
        setupConstraints()
        
        // 添加按钮动作
        cancelButton.addTarget(self, action: #selector(cancelButtonTapped), for: .touchUpInside)
        
        // 添加点击背景关闭的手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(backgroundTapped))
        tapGesture.delegate = self
        addGestureRecognizer(tapGesture)
    }
    
    private func setupConstraints() {
        containerView.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        tableView.translatesAutoresizingMaskIntoConstraints = false
        cancelButton.translatesAutoresizingMaskIntoConstraints = false
        
        // 容器约束
        NSLayoutConstraint.activate([
            containerView.centerXAnchor.constraint(equalTo: centerXAnchor),
            containerView.centerYAnchor.constraint(equalTo: centerYAnchor),
            containerView.widthAnchor.constraint(equalToConstant: kScreenWidth - 60)
        ])
        
        containerHeightConstraint = containerView.heightAnchor.constraint(equalToConstant: 0)
        containerHeightConstraint.isActive = true
        
        // 标题约束
        NSLayoutConstraint.activate([
            titleLabel.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 20),
            titleLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 20),
            titleLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -20)
        ])
        
        // 表格约束
        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 16),
            tableView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
            tableView.bottomAnchor.constraint(equalTo: cancelButton.topAnchor, constant: -16)
        ])
        
        // 取消按钮约束
        NSLayoutConstraint.activate([
            cancelButton.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 20),
            cancelButton.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -20),
            cancelButton.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -20),
            cancelButton.heightAnchor.constraint(equalToConstant: 44)
        ])
    }
    
    // 更新容器高度约束
    private func updateContainerConstraints() {
        let tableHeight = CGFloat(items.count) * DIMENSION_VALUE(50)
        let titleHeight = titleLabel.sizeThatFits(CGSize(width: 260, height: CGFloat.greatestFiniteMagnitude)).height
        let totalHeight = titleHeight + tableHeight + 44 + 20 + 16 + 16 + 20 // 标题高度 + 表格高度 + 按钮高度 + 各种间距
        
        if totalHeight > maxHeight {
            containerHeightConstraint.constant = maxHeight
            tableView.isScrollEnabled = true
        } else {
            containerHeightConstraint.constant = totalHeight
            tableView.isScrollEnabled = false
        }
        
        UIView.animate(withDuration: 0.3) {
            self.layoutIfNeeded()
        }
    }
    
    // MARK: - 显示和隐藏
    func show() {
        // 获取应用的主窗口
        guard let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else {
            return
        }
        
        self.alpha = 0
        self.frame = window.bounds
        window.addSubview(self)
        
        // 初始动画
        containerView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: {
            self.alpha = 1
            self.containerView.transform = .identity
        })
    }
    
    func hide() {
        UIView.animate(withDuration: 0.2, animations: {
            self.alpha = 0
            self.containerView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        }) { _ in
            self.removeFromSuperview()
        }
    }
    
    // MARK: - 按钮动作
    @objc private func cancelButtonTapped() {
        hide()
    }
    
    @objc private func backgroundTapped(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: self)
        if !containerView.frame.contains(location) {
            hide()
        }
    }
}

// MARK: - UITableView 数据源和代理
extension SelectionDialogView: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SelectionCell", for: indexPath) as! SelectionCell
        let item = items[indexPath.row]
        
        cell.configure(with: item, isSelected: indexPath.row == selectedIndex)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return DIMENSION_VALUE(50)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedIndex = indexPath.row
        tableView.reloadData()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            self.selectionHandler?(indexPath.row)
            self.hide()
        }
    }
}

// MARK: - 手势识别代理
extension SelectionDialogView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        return touch.view == self
    }
}

// MARK: - 自定义圆角单元格
class SelectionCell: UITableViewCell {
    
    private let iconImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        imageView.tintColor = .darkGray
        return imageView
    }()
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.font = DIMENSION_FONT_OF_SIZE(14)
        label.textColor = .white
        label.textAlignment = .center
        return label
    }()
    
    private let backView: UIView = {
        let view = UIView()
        view.backgroundColor = HexRGB(0x252A45)
        view.layer.cornerRadius = DIMENSION_VALUE(15)
        return view
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    private func setupUI() {
        // 设置单元格背景
        backgroundColor = .clear
        selectionStyle = .none
        
        // 添加子视图
        contentView.addSubview(backView)
        backView.addSubview(iconImageView)
        backView.addSubview(titleLabel)
        // 设置约束
        setupConstraints()
    }
    
    private func setupConstraints() {
      
        backView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(10))
            make.top.equalToSuperview().offset(DIMENSION_VALUE(5))
            make.right.equalToSuperview().offset(DIMENSION_VALUE(-10))
            make.bottom.equalToSuperview().offset(DIMENSION_VALUE(-5))
        }
        
        iconImageView.snp.makeConstraints { make in
            make.width.height.equalTo(DIMENSION_VALUE(25))
            make.centerY.equalTo(backView.snp_centerY)
            make.left.equalToSuperview().offset(DIMENSION_VALUE(10))
        }
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(iconImageView.snp_right).offset(DIMENSION_VALUE(10))
            make.right.equalToSuperview().offset(DIMENSION_VALUE(-10))
            make.centerY.equalToSuperview()
        }
    }
    func configure(with item: SelectItemModel, isSelected: Bool) {
        titleLabel.text = item.name
        iconImageView.image = UIImage(named: item.iconName)
    }
}

struct SelectItemModel {
    let name: String // 屏幕尺寸名字
   
    let iconName:String
  
    init(name: String,iconName:String) {
        self.name = name
        self.iconName = iconName
    }
}
